package com.customization.unionpay.contract.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.mobile.webservices.workflow.WorkflowRequestBean;
import weaver.mobile.webservices.workflow.soa.*;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContractWorkflowServiceUtils {

    private static final Log logger = LogFactory.getLog(ContractWorkflowServiceUtils.class);

    private static String WFID_HTBA_SK = "4000096";// 收入合同备案流程
    private static String WFID_HTBA_FK = "4000119";// 常规支出合同备案流程
    private static String WFID_HTBA_SZ = "4000147";// 收支两用合同备案流程
    private static String WFID_HTBG_SR = "4000103";// 收入合同变更备案审批（补充合同）
    private static String WFID_HTBG_ZC = "4000150";//常规支出合同变更备案审批（补充合同）
    private static String WFID_HTYJ = "4000162";//合同移交流程
    private static String WFID_HTJT = "74";//合同计提流程 //TODO: 根据现场环境调整

    /**
     * 创建收款合同备案流程
     * 《收入合同备案流程》
     *
     * @param json
     * @param user
     * @return
     */
    public static boolean createWorkflowOfSKHTBA(JSONObject json, User user) {
        Map map = getSynDataSKBaseInfo(json);

        List<String> valueList = Lists.newArrayList("htmc","htbh","htcbjgmc","htcbbmmc","htcbryxm","htgdr","htqdsj","htdqr","htskysbde","yyyhtfj","zhtbh","glzht","htlsbz","htsfkgx","htywlx");
        JSONArray signerJson = json.getJSONArray("signingParties");
        List signerList = getSignerList(signerJson);
        int requestid = createWorkflow(WFID_HTBA_SK, "收入合同备案流程", map, valueList, signerList, user);

        if (requestid > 0) {
            return true;
        } else {
            return false;
        }
    }

    private static Map<String, Object> getSynDataSKBaseInfo(JSONObject json) {
        Map result = new HashMap();
        List<String> paramList = new ArrayList<>(json.keySet());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("contractName","htmc");
        paramMap.put("contractNumber","htbh");
        paramMap.put("contractOrg","htcbjgmc");
        paramMap.put("contractDept","htcbbmmc");
        paramMap.put("contractUser","htcbryxm");
        paramMap.put("contractFilingDate","htgdr");
        paramMap.put("contractSignDate","htqdsj");
        paramMap.put("contractExpireDate","htdqr");
        paramMap.put("contractPresetAmount","htskysbde");
        paramMap.put("attachment","yyyhtfj");
        paramMap.put("contractMainNum","zhtbh");
        paramMap.put("relatedMainNum","glzht");
        paramMap.put("remark","htlsbz");
        paramMap.put("payRelation","htsfkgx");
        paramMap.put("contractBusiType","htywlx");

        for (String param : paramList) {
            String key = paramMap.get(param);
            if (null != key && !"".equals(key)) {
                result.put(key, json.get(param));
            }
        }
        return result;
    }
//
//    private static Map<String, Object> getBaseInfo(int userID, Integer requestid) {
//        //创建日期 时间 创建人
//        String modedatacreatedate = com.weaver.general.TimeUtil.getCurrentDateString();
//        String modedatacreatetime = com.weaver.general.TimeUtil.getOnlyCurrentTimeString();
//        int modedatacreater = userID;
//
//        Map<String, Object> dataMap = new HashMap<>();
//        if (null != requestid) {
//            dataMap.put("requestId", requestid);
//        }
//        dataMap.put("modedatacreater", modedatacreater);
//        dataMap.put("modedatacreatedate", modedatacreatedate);
//        dataMap.put("modedatacreatetime", modedatacreatetime);
//        dataMap.put("modedatamodifier", modedatacreater);
//        dataMap.put("modedatamodifydatetime", modedatacreatedate + " " + modedatacreatetime);
////        dataMap.put("formmodeid",);
////        dataMap.put("MODEUUID",);
////        dataMap.put("form_biz_id",); //TODO: 获取逻辑ß
//        return dataMap;
//    }

    /**
     * 创建付款合同备案流程
     * 《常规支出合同备案流程》
     *
     * @param json
     * @param user
     * @return
     */
    public static boolean createWorkflowOfFKHTBA(JSONObject json, User user) {

        Map map = getSynDataFKBaseInfo(json);

        List<String> valueList = Lists.newArrayList("htmc", "htbh", "htjbjg", "htjbbm", "htjbr", "htgdr", "htqdsj", "htdqr", "htskysbde", "htfkysbde", "yyyhtfj", "zhtbh", "glzht", "sfjcht", "sfsjdbmzhsfkjh", "htlszygy", "htlsbz", "htsfkgx", "htywlx","htglbhwb","sfjc");
        map.put("htsfkgx", 2);
        JSONArray signerJson = json.getJSONArray("signingParties");
        List signerList = getSignerList(signerJson);
        int requestid = createWorkflow(WFID_HTBA_FK, "常规支出合同备案流程", map, valueList, signerList, user);

        if (requestid > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 创建收支两用合同备案流程
     * 收支两用合同备案流程
     *
     * @param json
     * @param user
     */
    public static boolean createWorkflowOfSZHTBA(JSONObject json, User user) {
        Map map = getSynDataSZBaseInfo(json);
        List<String> valueList = Lists.newArrayList("htmc", "htbh", "htjbjg", "htjbbm", "htjbr", "htgdr", "htqdsj", "htdqr", "htskysbde", "yyyhtfj", "zhtbh", "glzht", "htlsbz", "htsfkgx", "htywlx", "htfkysbde", "sfjcht", "sfsjdbmzhsfkjh", "htlszygy","htglbhwb","sfjc");
        JSONArray signerJson = json.getJSONArray("signingParties");
        List signerList = getSignerList(signerJson);
        int requestid = createWorkflow(WFID_HTBA_SZ, "收支两用合同备案流程", map, valueList, signerList, user);
        if (requestid > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static List getSignerList(JSONArray signerJson) {
        if (null == signerJson) {
            return null;
        }
        List<String> keyList = Lists.newArrayList("sfylf", "qyfmc", "qyftyshxydm", "khyh", "zh", "yhzh");
        List result = Lists.newArrayList();
        for (int i = 0; i < signerJson.size(); i++) {
            JSONObject json = signerJson.getJSONObject(i);
            Map map = new HashMap();
            keyList.forEach(key -> {
                map.put(key, json.getString(key));
            });
            result.add(map);
        }
        return result;
    }

    private static Map getSynDataSZBaseInfo(JSONObject json) {
        Map result = new HashMap();
        List<String> paramList = new ArrayList<>(json.keySet());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("contractName","htmc");
        paramMap.put("contractNumber","htbh");
        paramMap.put("contractOrg","htjbjg");
        paramMap.put("contractDept","htjbbm");
        paramMap.put("contractUser","htjbr");
        paramMap.put("contractFilingDate","htgdr");
        paramMap.put("contractSignDate","htqdsj");
        paramMap.put("contractExpireDate","htdqr");
        paramMap.put("contractPresetAmount","htskysbde");
        paramMap.put("attachment","yyyhtfj");
        paramMap.put("contractMainNum","zhtbh");
        paramMap.put("relatedMainNum","glzht");
        paramMap.put("remark","htlsbz");
        paramMap.put("payRelation","htsfkgx");
        paramMap.put("contractBusiType","htywlx");
        paramMap.put("expendRecordPresetAmount","htfkysbde");
        paramMap.put("expendRecordCollectiveProcurement","sfjcht");
        paramMap.put("expendRecordMultiDepartment","sfsjdbmzhsfkjh");
        paramMap.put("expendRecordAbstract","htlszygy");
        paramMap.put("expendRecordRelatedNo","htglbhwb");
        paramMap.put("sfjc","sfjc");//是否集采

        for (String param : paramList) {
            String key = paramMap.get(param);
            if (null != key && !"".equals(key)) {
                result.put(key, json.get(param));
            }
        }
        return result;
    }

    /**
     * 合同变更备案
     * 常规支出合同变更备案审批（补充合同）
     * 收入合同变更备案审批（补充合同）
     *
     * @param map
     * @return
     */
    public static boolean createWorkflowOfHTBGBA(Map<String, String> map, JSONObject htmx) {
        String htsfkgx = map.get("htsfkgx");

        if ("1".equals(htsfkgx)) {
            // 收款合同 (htsfkgx = 1)
            String userIdStr = map.get("htcbryxm");
            if (null != userIdStr) {
                int userId = Integer.parseInt(userIdStr);
                User user = new User(userId);
                return createWorkflowOfSKHTBG(map, htmx, user);
            }
        } else {
            // 付款合同 (htsfkgx = 2)
            String userIdStr = map.get("htjbr");
            if (null != userIdStr) {
                int userId = Integer.parseInt(userIdStr);
                User user = new User(userId);
                return createWorkflowOfFKHTBG(map, htmx, user);
            }
        }
        return false;
    }

    /**
     * 收入合同变更备案审批（补充合同）
     *
     * @param map
     * @param user
     * @return
     */
    private static boolean createWorkflowOfSKHTBG(Map<String, String> map, JSONObject htmx, User user) {
        List<String> valueList = Lists.newArrayList("htmc", "htbh", "htcbjgmc", "htcbbmmc", "htcbryxm", "htgdr", "htqdsj", "htdqr", "htskysbde", "htfkysbde", "yyyhtfj", "zhtbh", "glzht", "sfjcht", "sfsjdbmzxsfkjh", "htlszygy", "htlsbz", "htsfkgx", "htywlx");
        int requestid = createWorkflow(WFID_HTBG_SR, "收入合同变更备案审批（补充合同）", map, valueList, htmx, user);
        if (requestid > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 常规支出合同变更备案审批（补充合同）
     *
     * @param map
     * @param user
     * @return
     */
    private static boolean createWorkflowOfFKHTBG(Map<String, String> map, JSONObject htmx, User user) {
        List<String> valueList = Lists.newArrayList("htmc", "htbh", "htcbjgmc", "htcbbmmc", "htcbryxm", "htgdr", "htqdsj", "htdqr", "htskysbde", "htfkysbde", "htfkysbde", "yyyhtfj", "zhtbh", "glzht", "sfjcht", "sfsjdbmzxsfkjh", "htlszygy", "htlsbz", "htsfkgx", "htywlx");
        int requestid = createWorkflow(WFID_HTBG_ZC, "常规支出合同变更备案审批（补充合同）", map, valueList, htmx, user);
        if (requestid > 0) {
            return true;
        } else {
            return false;
        }
    }

    private static Map<String, Object> getSynDataFKBaseInfo(JSONObject json) {
        Map result = new HashMap();
        List<String> paramList = new ArrayList<>(json.keySet());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("contractName","htmc");
        paramMap.put("contractNumber","htbh");
        paramMap.put("contractOrg","htjbjg");
        paramMap.put("contractDept","htjbbm");
        paramMap.put("contractUser","htjbr");
        paramMap.put("contractFilingDate","htgdr");
        paramMap.put("contractSignDate","htqdsj");
        paramMap.put("contractExpireDate","htdqr");
        paramMap.put("contractPresetAmount","htskysbde");
        paramMap.put("attachment","yyyhtfj");
        paramMap.put("contractMainNum","zhtbh");
        paramMap.put("relatedMainNum","glzht");
        paramMap.put("remark","htlsbz");
        paramMap.put("payRelation","htsfkgx");
        paramMap.put("contractBusiType","htywlx");
        paramMap.put("expendRecordPresetAmount","htfkysbde");
        paramMap.put("expendRecordCollectiveProcurement","sfjcht");
        paramMap.put("expendRecordMultiDepartment","sfsjdbmzhsfkjh");
        paramMap.put("expendRecordAbstract","htlszygy");
        paramMap.put("expendRecordRelatedNo","htglbhwb");
        paramMap.put("sfjc","sfjc"); // 是否集采
        for (String param : paramList) {
            String key = paramMap.get(param);
            if (null != key && !"".equals(key)) {
                result.put(key, json.get(param));
            }
        }
        return result;
    }

    public static int createWorkflow(String workflowId, String workflowName, Map data, List<String> valueList, JSONObject htmx, User user) {
        if (!StringUtils.isNotBlank(workflowId)) {
            logger.info("createWorkflow=========================err：未配置" + workflowName + "流程ID");
            return -1;
        }

        Map<String, Object> wfMap = new HashMap<>();
        valueList.forEach(key -> {
            wfMap.put(key, data.get(key));
        });
        // wfMap.putAll(getSynDataBaseInfo(user.getUID()));

        int requestid = createWFMX(user, workflowId, wfMap, htmx);

        logger.info("createWorkflow=========================doCreateWorkflowRequest requestid" + requestid);
        return requestid;
    }

    public static int createWorkflowByJson(String workflowId, String workflowName, JSONObject data, List<String> valueList, JSONObject htmx, User user) {
        if (!StringUtils.isNotBlank(workflowId)) {
            logger.info("createWorkflow=========================err：未配置" + workflowName + "流程ID");
            return -1;
        }

        Map<String, Object> wfMap = new HashMap<>();
        valueList.forEach(key -> {
            wfMap.put(key, data.get(key));
        });
        // wfMap.putAll(getSynDataBaseInfo(user.getUID()));

        int requestid = createWFMX(user, workflowId, wfMap, htmx);

        logger.info("createWorkflow=========================doCreateWorkflowRequest requestid" + requestid);
        return requestid;
    }

    private static int createWFMX(User user, String wfid, Map<String, Object> wfMap, JSONObject htmx) {
        Boolean ret = false;
        int newrequestid = 0;
        try {
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            RecordSet rsData = new RecordSet();

            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String workflowname = "";
            String formid = "";
            String wftablename = "";
            if (!"".equals(wfid)) {
                //主表开始
                String sql = "select workflowname,formid,isbill  from workflow_base  where  id=" + wfid;
                rs.executeSql(sql);
                if (rs.next()) {
                    workflowname = rs.getString("workflowname");
                    formid = rs.getString("formid");
                }
                wftablename = getNameById(formid);
                weaver.general.DateUtil dateUtil = new weaver.general.DateUtil();

                //流程请求标题
                String requestname = dateUtil.getWFTitleNew("" + wfid, "" + user.getUID(), "" + resourceComInfo.getLastname("" + user.getUID()), user.getLogintype());
                if ("".equals(requestname)) {
                    requestname = " " + workflowname + "-" + resourceComInfo.getLastname("" + user.getUID()) + "-" + TimeUtil.getCurrentDateString();
                }
                RequestInfo ri = new RequestInfo();
                ri.setIsNextFlow("0"); //是否创建后流转流程. 0:不流转. 1:流转
                ri.setDescription(requestname);
                ri.setWorkflowid(wfid); //流程ID
                ri.setCreatorid("" + user.getUID());  //创建人
                ri.setRequestlevel("0");  //紧急程度
                MainTableInfo mi = new MainTableInfo();
                // 主表属性值
                List<String> keyList = new ArrayList<>(wfMap.keySet());
                for (int i = 0; i < keyList.size(); i++) {
                    String key = keyList.get(i);
                    Property property = new Property();
                    property.setName(key);
                    property.setValue(Util.null2String(wfMap.get(key)));
                    mi.addProperty(property);
                }

                Property applypart = new Property();
                applypart.setName("apply_part");
                applypart.setValue(Util.null2String(user.getUserDepartment()));
                mi.addProperty(applypart);

                DetailTableInfo detailTableInfo = new DetailTableInfo();
                DetailTable[] detailTablearray = new DetailTable[1];
                WorkflowRequestBean wfResObj = new WorkflowRequestBean();
                wfResObj.setRemark("");
                wfResObj.setClientType("0");
                wfResObj.setClientIP(user.getLoginip());


                int orderid = 1;

                int htmxLength = 0;
                if (htmx.keySet() != null) {
                    htmxLength = htmx.keySet().size();
                }

                if (htmxLength > 0) {
                    int index = 0;
                    while (index < htmxLength) {
                        index++;
                        String dtltablename = wftablename + "_dt" + index;
                        JSONArray htmxData = htmx.getJSONArray(dtltablename);
                        if (null != htmxData) {
                            int rowNum = 0;
                            List<String> list = new ArrayList<>();
                            String mainFormtableId = new WorkflowComInfo().getFormId(wfid);
                            if (!mainFormtableId.isEmpty()) {
                                rs.executeQuery("select fieldname from workflow_billfield where billid =? AND viewtype=1", mainFormtableId);//固定查明细表1字段
                                while (rs.next()) {
                                    String fieldName = Util.null2String(rs.getString("fieldname"));
                                    if (!fieldName.isEmpty()) list.add(fieldName);
                                }
                            }
                            DetailTable detailTable = new DetailTable();
                            //一个明细
                            detailTable.setId(orderid + "");
                            detailTable.setTableDBName(dtltablename);
                            //设置行
                            List<Row> rows = new ArrayList<Row>();
                            List<JSONObject> rowList = Lists.newArrayList();
                            for (int i = 0; i < htmxData.size(); i++) {
                                rowList.add(htmxData.getJSONObject(i));
                            }
                            if (rowList.size() > 0) {
                                for (int i = 0; i < rowList.size(); i++) {
                                    Row row = new Row();
                                    int size = list.size();
                                    row.setId(rowNum + "");
                                    Cell[] cellarray = new Cell[size];
                                    int cellNum = 0;
                                    JSONObject map = rowList.get(i);

                                    List<String> mxKeyList = Lists.newArrayList(map.keySet());
                                    for (int j = 0; j < mxKeyList.size(); j++) {
                                        String mxKey = mxKeyList.get(j);
                                        Cell cell = new Cell();
                                        cell.setName(mxKey);
                                        cell.setValue(Util.null2String(map.get(mxKey)));
                                        cellarray[cellNum++] = cell;
                                    }

                                    row.setCell(cellarray);
                                    rowNum++;
                                    rows.add(row);
                                }

                            }
                            if (rows != null && rows.size() > 0) {
                                Row[] rowarray = (Row[]) rows.toArray(new Row[rows.size()]);
                                detailTable.setRow(rowarray);
                            }
                            detailTablearray[(orderid - 1)] = detailTable;
                            orderid++;
                        }
                    }
                }
                detailTableInfo.setDetailTable(detailTablearray);
                ri.setDetailTableInfo(detailTableInfo);
                ri.setMainTableInfo(mi);
                ri.setLanguageid(user.getLanguage());
                newrequestid = Util.getIntValue(new RequestService().createRequest(ri, wfResObj), 0);
                // 只新建流程 不修改状态
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newrequestid;
    }

    public static int createWorkflow(String workflowId, String workflowName, Map data, List<String> valueList, List signerList, User user) {
        if (!StringUtils.isNotBlank(workflowId)) {
            logger.info("createWorkflow=========================err：未配置" + workflowName + "流程ID");
            return -1;
        }

        Map<String, Object> wfMap = new HashMap<>();
        valueList.forEach(key -> {
            wfMap.put(key, data.get(key));
        });

        int requestid = createWF(user, workflowId, wfMap, signerList);

        logger.info("createWorkflow=========================doCreateWorkflowRequest requestid" + requestid);
        return requestid;
    }

    /**
     * 创建流程
     *
     * @param
     * @param user 当前用户
     * @param wfid 流程id
     * @return
     */
    public static int createWF(User user, String wfid, Map<String, Object> wfMap, List<Map<String, String>> signerList) {
        Boolean ret = false;
        int newrequestid = 0;
        try {
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            RecordSet rsData = new RecordSet();

            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String workflowname = "";
            String formid = "";
            String wftablename = "";
            if (!"".equals(wfid)) {
                //主表开始
                String sql = "select workflowname,formid,isbill  from workflow_base  where  id=" + wfid;
                rs.executeQuery(sql);
                if (rs.next()) {
                    workflowname = rs.getString("workflowname");
                    formid = rs.getString("formid");
                }
                wftablename = getNameById(formid);
                weaver.general.DateUtil dateUtil = new weaver.general.DateUtil();

                //流程请求标题
                String requestname = dateUtil.getWFTitleNew("" + wfid, "" + user.getUID(), "" + resourceComInfo.getLastname("" + user.getUID()), user.getLogintype());
                if ("".equals(requestname)) {
                    requestname = " " + workflowname + "-" + resourceComInfo.getLastname("" + user.getUID()) + "-" + TimeUtil.getCurrentDateString();
                }
                RequestInfo ri = new RequestInfo();
                ri.setIsNextFlow("0"); //是否创建后流转流程. 0:不流转. 1:流转
                ri.setDescription(requestname);
                ri.setWorkflowid(wfid); //流程ID
                ri.setCreatorid("" + user.getUID());  //创建人
                ri.setRequestlevel("0");  //紧急程度
                MainTableInfo mi = new MainTableInfo();
                // 主表属性值
                List<String> keyList = new ArrayList<>(wfMap.keySet());
                for (int i = 0; i < keyList.size(); i++) {
                    String key = keyList.get(i);
                    Property property = new Property();
                    property.setName(key);
                    property.setValue(Util.null2String(wfMap.get(key)));
                    mi.addProperty(property);
                }

                Property applypart = new Property();
                applypart.setName("apply_part");
                applypart.setValue(Util.null2String(user.getUserDepartment()));
                mi.addProperty(applypart);

                DetailTableInfo detailTableInfo = new DetailTableInfo();
                DetailTable[] detailTablearray = new DetailTable[1];
                WorkflowRequestBean wfResObj = new WorkflowRequestBean();
                wfResObj.setRemark("");
                wfResObj.setClientType("0");
                wfResObj.setClientIP(user.getLoginip());


                int orderid = 1;
                int rowNum = 0;
                List<String> list = new ArrayList<>();
                String mainFormtableId = new WorkflowComInfo().getFormId(wfid);
                if (!mainFormtableId.isEmpty()) {
                    rs.executeQuery("select fieldname from workflow_billfield where billid =? AND viewtype=1", mainFormtableId);//固定查明细表1字段
                    while (rs.next()) {
                        String fieldName = Util.null2String(rs.getString("fieldname"));
                        if (!fieldName.isEmpty()) list.add(fieldName);
                    }
                }
                DetailTable detailTable = new DetailTable();
                //一个明细
                detailTable.setId(orderid + "");
                String dtltablename = wftablename + "_dt1";
                detailTable.setTableDBName(dtltablename);
                //设置行
                List<Row> rows = new ArrayList<Row>();

                if (null != signerList) {
                    for (int i = 0; i < signerList.size(); i++) {
                        Row row = new Row();
                        Map<String, String> map = signerList.get(i);
                        // List<String> mxKeyList = Lists.newArrayList(map.keySet());
                        //只记录转换后的签约方id
                        List<String> mxKeyList = Lists.newArrayList("qyfmc");


                        int size = mxKeyList.size();
                        row.setId(rowNum + "");
                        Cell[] cellarray = new Cell[size];
                        int cellNum = 0;

                        for (int j = 0; j < size; j++) {
                            String mxKey = mxKeyList.get(j);
                            Cell cell = new Cell();
                            cell.setName(mxKey);
                            cell.setValue(Util.null2String(map.get(mxKey)));
                            cellarray[cellNum++] = cell;
                        }

                        row.setCell(cellarray);
                        rowNum++;
                        rows.add(row);
                    }

                }
                if (rows != null && rows.size() > 0) {
                    Row[] rowarray = (Row[]) rows.toArray(new Row[rows.size()]);
                    detailTable.setRow(rowarray);
                }
                detailTablearray[(orderid - 1)] = detailTable;
                detailTableInfo.setDetailTable(detailTablearray);
                ri.setDetailTableInfo(detailTableInfo);
                ri.setMainTableInfo(mi);
                ri.setLanguageid(user.getLanguage());
                newrequestid = Util.getIntValue(new RequestService().createRequest(ri, wfResObj), 0);
                // 只新建流程 不修改状态
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newrequestid;
    }

    public static String getMinModeIdByFormId(String formid) {
        if (StringUtils.isNotBlank(formid)) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select min(id) as id from modeinfo  where isdelete=0 and formid=?", new Object[]{formid});
            if (rs.next()) {
                return rs.getString("id");
            }
        }

        return "";
    }

    public static String getFormIdByFormName(String formName) {
        if (!"".equals(formName)) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from workflow_bill where tablename=?", new Object[]{formName});
            if (rs.next()) {
                return rs.getString("id");
            }
        }

        return "";
    }

    public static String getNameById(String var0) {
        RecordSet var1 = new RecordSet();
        String var2 = "";
        String var3 = "select tablename from workflow_bill where id=?";
        var1.executeQuery(var3, new Object[]{var0});
        if (var1.next()) {
            var2 = var1.getString("tablename");
        }

        return var2;
    }

    /**
     *
     * @param json
     * @param user
     * @return
     */
    public static boolean createWorkflowOfHTJT(JSONObject jsonObject,JSONObject json, User user) {
        List<String> valueList = Lists.newArrayList("htmc","htbh","htjbjg","htjbbm","htjbr","htqdsj","htdqr","htfkysbde","glzht","htywlx","htzl","htbhsje");

        String sql = "select formid  from workflow_base  where  id=" + WFID_HTJT;
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        String formid = "";
        if (rs.next()) {
            formid = rs.getString("formid");
        }
        String wftablename = getNameById(formid);
        JSONObject htmx = new JSONObject();
        htmx.put(wftablename+"_dt1",json.get("mx1"));
        htmx.put(wftablename+"_dt2",json.get("mx2"));

        int requestid = createWorkflowByJson(WFID_HTJT, "合同计提（履约进度评估）流程", jsonObject, valueList, htmx, user);
        if (requestid > 0) {
            return true;
        } else {
            return false;
        }
    }
}
